<?php

/**
 * approval actions.
 *
 * @package    student_manager
 * @subpackage approval
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class approvalActions extends autoapprovalActions
{

protected function IsGroupApproved($module, $objectId){
   //get group id of current user
    $c = new Criteria();
    $c->add(sfGuardUserGroupPeer::USER_ID , $this->getUser()->getGuardUser()->getId());
    $userGroup = sfGuardUserGroupPeer::doSelectOne($c);
    if (!$userGroup) return false;
    $groupId = $userGroup->getGroupId();
    
    $c = new Criteria();
    $c->add(ApprovalPeer::TYPE , CommonValues::$gApprovalType['key'][$module]);
    $c->add(ApprovalPeer::OBJECT_ID , $objectId);
    $approvals = ApprovalPeer::doSelect($c);
    //is approved once
    foreach ($approvals as $approval){
        $userId = $approval->getUserId();
        
        $c = new Criteria();
        $c->add(sfGuardUserGroupPeer::USER_ID , $userId);
        $userGroup = sfGuardUserGroupPeer::doSelectOne($c);
        //this user have approved already
        if ($userGroup && $userGroup->getGroupId() == $groupId) 
            return true;
    }
    return false;
}
public  function executeListApprovalObject(){      
     
     $this->getResponse()->setTitle('WMS-'.$this->getRequestParameter('mod').'-Approval-List');
    $this->backURL = $this->getRequestParameter('backURL');
    $this->backURL = str_replace('~1', '/', $this->backURL);
    $this->backURL = str_replace('~2', '?', $this->backURL);
    $this->backURL = str_replace('~3', '&', $this->backURL);
    $this->backURL = str_replace('~4', '=', $this->backURL);
    //echo $this->backURL; exit();
    $AuthenticationMain = $this->getRequestParameter('authenticationMain');
    $AuthenticationSub = $this->getRequestParameter('authenticationSub');
    
    
    if (!$AuthenticationMain || !$AuthenticationSub || !($this->getUser()->hasCredential($AuthenticationMain) || $this->getUser()->hasCredential($AuthenticationSub)) )
        $this->redirect($this->backURL);
        
    $module = $this->getRequestParameter('mod');
    if (!$module)
        $this->redirect($this->backURL);
        
    $Objectlist = array();
    switch ($module) {    
    case 'BOM':
        $c = new Criteria();
        $c->add(BOMPeer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);
        $c->addAscendingOrderByColumn(BOMPeer::PUBLISHTIME );
        $Objectlist = BOMPeer::doSelect($c);
        break;
    case 'MRSUB':
        if ($this->getUser()->hasCredential('APPROVE_MRSUBSTK') && $this->getUser()->hasCredential('APPROVE_MRSUBFTR')) {
            $c = new Criteria();
            $c->add(MR2Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);    
            $c->addAscendingOrderByColumn(MR2Peer::PUBLISHTIME );
            $Objectlist = MR2Peer::doSelect($c);        
        } elseif ($this->getUser()->hasCredential('APPROVE_MRSUBSTK')){
            $c = new Criteria();
            $c->add(MR2Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);    
            $c->add(MR2Peer::CATEGORY , CommonValues::$gMRCategory['key']['Stock']);
            $c->addAscendingOrderByColumn(MR2Peer::PUBLISHTIME );
            $Objectlist = MR2Peer::doSelect($c);        
        } elseif ($this->getUser()->hasCredential('APPROVE_MRSUBFTR')){
            $c = new Criteria();
            $c->add(MR2Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);    
            $c->add(MR2Peer::CATEGORY , CommonValues::$gMRCategory['key']['Factory']);
            $c->addAscendingOrderByColumn(MR2Peer::PUBLISHTIME );
            $Objectlist = MR2Peer::doSelect($c);        
        }
        break;
    case 'MRRAW':
        $c = new Criteria();
        $c->add(MR3Peer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);    
        $c->addAscendingOrderByColumn(MR3Peer::PUBLISHTIME );
        $Objectlist = MR3Peer::doSelect($c);
        break;
    case 'PO':
        $c = new Criteria();
        $c->add(POPeer::APPROVALSTATUS , CommonValues::$gMRApprovalStatus['key']['Waiting for approval']);    
        $c->addAscendingOrderByColumn(POPeer::PUBLISHTIME );
        $Objectlist = POPeer::doSelect($c);
        break;
    default:
        return $this->redirect($this->backURL);
        break;
    }
    $this->ObjectneedApprovalList = array();
    $count = 0;    
        
    //if approve normal
    if ($this->getUser()->hasCredential($AuthenticationMain) || $this->getUser()->hasCredential($AuthenticationSub)){                
        foreach ($Objectlist as $object){
            if ( !$this->IsGroupApproved($module, $object->getId())) {
                $this->ObjectneedApprovalList[$count] = $object;
                $count++;
            }
        }
    }
    
    $this->module = $module;
}
public function executeRejectObject(){
     $this->getResponse()->setTitle('WMS-Reject-Approval');
    $objectId = $this->getRequestParameter('id');
    $module = $this->getRequestParameter('mod');
    //echo $objectId; exit();
    $this->backURL = $this->getRequestParameter('backURL');
    $this->backURL = str_replace('~1', '/', $this->backURL);
    $this->backURL = str_replace('~2', '?', $this->backURL);
    $this->backURL = str_replace('~3', '&', $this->backURL);
    $this->backURL = str_replace('~4', '=', $this->backURL);
    //echo $this->backURL; exit();
    $AuthenticationMain = $this->getRequestParameter('authenticationMain');
    $AuthenticationSub = $this->getRequestParameter('authenticationSub');
    
    
    if (!$AuthenticationMain || !$AuthenticationSub || !($this->getUser()->hasCredential($AuthenticationMain) || $this->getUser()->hasCredential($AuthenticationSub)) )
        $this->redirect($this->backURL);
        
        
    if (!$objectId || !$module) 
        return $this->redirect($this->backURL);
        
    $object = null;
    
    switch ($module) {    
    case 'BOM':
        $object = BOMPeer::retrieveByPK($objectId);
        break;
    case 'MRSUB':
        $object = MR2Peer::retrieveByPK($objectId);
        $module = 'MR2';
        break;
    case 'MRRAW':
        $object = MR3Peer::retrieveByPK($objectId);
        $module = 'MR3';
        break;
    case 'PO':
        $object = POPeer::retrieveByPK($objectId);
        break;
    default:
        return $this->redirect($this->backURL);
        break;
    }
    
    
    if (!$object) 
        return $this->redirect($this->backURL);
    if (!$object->getApprovalStatus() || $object->getApprovalStatus() != CommonValues::$gMRApprovalStatus['key']['Waiting for approval'])
        return $this->redirect($this->backURL);
        
    $this->module = $module;
    $this->object = $object;    
}
public function executeApproveObject(){
     $this->getResponse()->setTitle('WMS-Approval');
    $objectId = $this->getRequestParameter('id');
    $module = $this->getRequestParameter('mod');
    //echo $objectId; exit();
    $this->backURL = $this->getRequestParameter('backURL');
    
    $this->backURL = str_replace('~1', '/', $this->backURL);
    $this->backURL = str_replace('~2', '?', $this->backURL);
    $this->backURL = str_replace('~3', '&', $this->backURL);
    $this->backURL = str_replace('~4', '=', $this->backURL);
    //echo $this->backURL; exit();
    $AuthenticationMain = $this->getRequestParameter('authenticationMain');
    $AuthenticationSub = $this->getRequestParameter('authenticationSub');
    
    
    if (!$AuthenticationMain || !$AuthenticationSub || !($this->getUser()->hasCredential($AuthenticationMain) || $this->getUser()->hasCredential($AuthenticationSub)) )
        $this->redirect($this->backURL);
        
        
    if (!$objectId || !$module) 
        return $this->redirect($this->backURL);
        
    $object = null;
    
    switch ($module) 
    {    
    case 'BOM':
        $object = BOMPeer::retrieveByPK($objectId);
        break;
    case 'MRSUB':
        $object = MR2Peer::retrieveByPK($objectId);
        break;
    case 'MRRAW':
        $object = MR3Peer::retrieveByPK($objectId);
        break;
    case 'PO':
        $object = POPeer::retrieveByPK($objectId);
        break;
    default:
        return $this->redirect($this->backURL);
        break;
    }    
    
    if (!$object) 
        return $this->redirect($this->backURL);
    if (!$object->getApprovalStatus() || $object->getApprovalStatus() != CommonValues::$gMRApprovalStatus['key']['Waiting for approval'])
        return $this->redirect($this->backURL);
    
    if ($this->IsGroupApproved($module, $objectId)) 
        return $this->redirect($this->backURL);        
        
    $approval = new Approval();
    $approval->setType( CommonValues::$gApprovalType['key'][$module]);
    $approval->setObjectId($objectId);
    $approval->setUserId($this->getUser()->getGuardUser()->getId());
    $approval->save();    
    
    if ($this->getUser()->hasCredential('APPROVE_FINAL')) 
    {
        $object->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);        
        $object->save();
        
        if ($module == 'BOM')
        {
            if ($object->getReviseId())
                $this->reviseBOMnew($object);
            else
                $this->approveBOM($object);
        } 
        elseif ($module =='PO')
        {
            if ($object->getReviseId())
                $this->revisePO($object);
            else
                $this->approvePO($object);
        }
        else 
        {
            if ($object->getReviseId())
                $this->reviseMR($object, $module);
            else
                $this->approveMR($object);
        }
    }
        
    if ($module == 'BOM') $name = $object->getWono();
    elseif ($module == 'PO') $name = $object->getPono();
    else $name = $object->getMrno();    
    
    $this->getUser()->setFlash('notice', "$name was approved successfully!");
    return $this->redirect($this->backURL);
}
public function reviseDAPO($newpo)
{
    $reviseId = $newpo->getReviseId();
    $oldPO = POPeer::retrieveByPK($reviseId);
    if (!$oldPO) return;

    $oldcomponentGroupId = $oldPO->getComponentgroupId();    
    $newcomponentGroupId = $newpo->getComponentgroupId();
    if (!$newcomponentGroupId) return;
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $newcomponentGroupId);
    $newcomponentsList = ComponentsPeer::doSelect($c);

    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldcomponentGroupId);
    $oldcomponentsList = ComponentsPeer::doSelect($c);
    if (!$newcomponentsList || !count($newcomponentsList)) return;
    $oldPO->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Revised']);
    $oldPO->save();
    $newpo->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['In progress']);
   // $newpo->set
    $newpo->save();
    $MRId = $newpo->getMrno();
    $mr = null;
    $compCate =$newpo->getCompcategory();
    if ($compCate == CommonValues::$gCompCategory['key']['Main Component']) {
        $mr = MRPeer::retrieveByPK($MRId);
    } elseif ($compCate == CommonValues::$gCompCategory['key']['Sub Component']) {
        $mr = MR2Peer::retrieveByPK($MRId);
    } else {
        $mr = MR3Peer::retrieveByPK($MRId);
    }

    if (!$mr) return;

    $MRCompGroupId = $mr->getComponentgroupId();
    if (!$MRCompGroupId)  return;
     echo "b1";
     
    foreach ( $newcomponentsList as $comps) {
        $compId = $comps->getComponentId();
        if (!$compId) continue;
        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldcomponentGroupId);
        $oldComps = ComponentsPeer::doSelectOne($c);
        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
        $MRComps = ComponentsPeer::doSelectOne($c);

        //update warehouse
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID , $compId);
        $Warehouse = WarehousePeer::doSelectOne($c);

        if ($oldComps){
            $comps->setQty4($oldComps->getQty4());
            $extra = $comps->getQty1() - $oldComps->getQty1();
            if ($extra < 0)
            {
                 $c = new Criteria();
                 $c->add(TallyInPeer::STATUS,  CommonValues::$gTLStatus['key']['Published']);        
                 $c->add(TallyInPeer::COMPONENTGROUP_ID,$oldcomponentGroupId);
                 $c->add(TallyInPeer::TALLYNO,$oldPO->getId());
                  
                 $tallyincheck = TallyInPeer::doSelect($c);
                        //tinh tong po de kiem tra so luong can giam cho conponent cua mr moi
                  $sumtitocheck = 0;
                  foreach ($tallyincheck as $ti)
                   {
                            $c = new Criteria();
                            $c->add(ComponentsPeer::COMPONENT_ID,$compId);
                            $c->add(ComponentsPeer::COMPONENTGROUP_ID,$ti->getComponentgroupId());
                            $compsti = ComponentsPeer::doSelectOne($c);
                            $sumtitocheck += $compsti->getQty1();
                   }
                   if (count($tallyincheck)>0)
                   {
                    if ($sumtitocheck <= $comps->getQty1() )  
                    {
                        $comps->setQty1($sumtitocheck) ;
                        //Khi ma so luong cua giam ma nho hon soluong cua cac tallyin thi 
                        //gan bang tong so luong tallyin cua po do
                         $extra = $comps->getQty1() - $oldComps->getQty1();
                    }
                   }
                
            }
           
           // $extra = $comps->getQty1() - $oldComps->getQty1();
            $comps->setQty4($comps->getQty4() + $extra);
            $comps->save();
            //cap nhat lai MR voi 1 luong tang giam tu PO
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() - $extra);
                $MRComps->save();
            }
            echo "<br>".$extra."<br>";            
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() - $extra >0 ? $Warehouse->getQtyrequested() - $extra: 0);
            $Warehouse->setQtyordered($Warehouse->getQtyordered() + $extra);
        } 
        //neu khong ton tai oldpo tuc la co comp
        /*
        else{
            $extra = $comps->getQty1();
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() - $extra);
                $MRComps->save();
            }
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() - $extra >0 ? $Warehouse->getQtyrequested() - $extra: 0);
            $Warehouse->setQtyordered($Warehouse->getQtyordered() + $extra);
        }
         * */
         
        $Warehouse->save();
    }
    //cap nhat lai trang thai complte cho MR
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
    $MRCompsList = ComponentsPeer::doSelect($c);

    //check MR complete
    $bComplete = true;
    foreach ($MRCompsList as $comps){
        if ($comps->getQty4() > 0) {
            $bComplete = false;
            break;
        }
    }
     if ($bComplete){
        $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
        $mr->save();
    }
     echo "b4";
          exit();
}

public function revisePO($po){

    $reviseId = $po->getReviseId();
    $rvPO = POPeer::retrieveByPK($reviseId);
    if (!$rvPO) return;

    $rvCompgroupId = $rvPO->getComponentgroupId();
    
    $componentGroupId = $po->getComponentgroupId();
    if (!$componentGroupId) return;

    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
    $componentsList = ComponentsPeer::doSelect($c);

    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompgroupId);
    $rvCompsList = ComponentsPeer::doSelect($c);

    if (!$componentsList || !count($componentsList)) return;

    $MRId = $po->getMrno();
    $mr = null;
    $compCate =$po->getCompcategory();
    if ($compCate == CommonValues::$gCompCategory['key']['Main Component']) {
        $mr = MRPeer::retrieveByPK($MRId);
    } elseif ($compCate == CommonValues::$gCompCategory['key']['Sub Component']) {
        $mr = MR2Peer::retrieveByPK($MRId);
    } else {
        $mr = MR3Peer::retrieveByPK($MRId);
    }

    if (!$mr) return;

    $MRCompGroupId = $mr->getComponentgroupId();
    if (!$MRCompGroupId)  return;

    foreach ( $componentsList as $comps) {
        $compId = $comps->getComponentId();

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompgroupId);
        $rvComps = ComponentsPeer::doSelectOne($c);

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
        $MRComps = ComponentsPeer::doSelectOne($c);

        //update warehouse
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID , $compId);
        $Warehouse = WarehousePeer::doSelectOne($c);

        if ($rvComps){
            $comps->setQty4($rvComps->getQty4());
            
            $extra = $comps->getQty1() - $rvComps->getQty1();
            $comps->setQty4($comps->getQty4() + $extra);
            $comps->save();
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() - $extra);
                $MRComps->save();
            }
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() - $extra >0 ? $Warehouse->getQtyrequested() - $extra: 0);
            $Warehouse->setQtyordered($Warehouse->getQtyordered() + $extra);
        } else{
            $extra = $comps->getQty1();
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() - $extra);
                $MRComps->save();
            }
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() - $extra >0 ? $Warehouse->getQtyrequested() - $extra: 0);
            $Warehouse->setQtyordered($Warehouse->getQtyordered() + $extra);
        }
        $Warehouse->save();
    }

    foreach ( $rvCompsList as $rvComps) {
        $compId = $rvComps->getComponentId();

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $comps = ComponentsPeer::doSelectOne($c);

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENT_ID , $compId);
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
        $MRComps = ComponentsPeer::doSelectOne($c);

        //update warehouse
        $c = new Criteria();
        $c->add(WarehousePeer::COMPONENT_ID , $compId);
        $Warehouse = WarehousePeer::doSelectOne($c);

        if (!$comps){
            $extra = $rvComps->getQty1();
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() + $extra);
                $MRComps->save();
            }
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() + $extra );
            $Warehouse->setQtyordered($Warehouse->getQtyordered() - $extra > 0? $Warehouse->getQtyordered() - $extra: 0);
        }
        $Warehouse->save();
    }

    $rvPO->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Revised']);
    $rvPO->save();

    $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['In progress']);
    $po->save();

    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
    $MRCompsList = ComponentsPeer::doSelect($c);

    //check MR complete
    $bComplete = true;
    foreach ($MRCompsList as $comps){
        if ($comps->getQty4() > 0) {
            $bComplete = false;
            break;
        }
    }

     if ($bComplete){
        $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
        $mr->save();
    }
}
public function approvePO($po){

        $componentGroupId = $po->getComponentgroupId();
        if (!$componentGroupId) {
            return;
        }

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $componentsList = ComponentsPeer::doSelect($c);

        if (!$componentsList || !count($componentsList)) {
            return;
        }

        $MRId = $po->getMrno();
        $mr = null;
        $compCate =$po->getCompcategory();
        if ($compCate == CommonValues::$gCompCategory['key']['Main Component']) {
            $mr = MRPeer::retrieveByPK($MRId);
        } elseif ($compCate == CommonValues::$gCompCategory['key']['Sub Component']) {
            $mr = MR2Peer::retrieveByPK($MRId);
        } else {
            $mr = MR3Peer::retrieveByPK($MRId);
        }

        if (!$mr) {
            return;
        }

        $MRCompGroupId = $mr->getComponentgroupId();
        if (!$MRCompGroupId) {
            return;
        }

        foreach ( $componentsList as $comps) {
            $compId = $comps->getComponentId();
            $c = new Criteria();
            $c->add(ComponentsPeer::COMPONENT_ID , $compId);
            $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
            $MRComps = ComponentsPeer::doSelectOne($c);
            if ($MRComps){
                $MRComps->setQty4($MRComps->getQty4() - $comps->getQty1());
                $MRComps->save();
            }

            //update warehouse
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $compId);
            $Warehouse = WarehousePeer::doSelectOne($c);

            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() - $comps->getQty1() > 0 ? $Warehouse->getQtyrequested() - $comps->getQty1(): 0);
            $Warehouse->setQtyordered($Warehouse->getQtyordered() + $comps->getQty1());

            $Warehouse->save();
        }

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRCompGroupId);
        $MRCompsList = ComponentsPeer::doSelect($c);

        //check MR complete
        $bComplete = true;
        foreach ($MRCompsList as $comps)
        {
            if ($comps->getQty4() > 0) 
            {
                $bComplete = false;
                break;
            }
        }

        if ($bComplete)
        {
            $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
            $mr->save();
        }
}
public function approveMR($mr){

        $componentGroupId = $mr->getComponentgroupId();
        if (!$componentGroupId) {
            return;
        }

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $componentsList = ComponentsPeer::doSelect($c);

        if (!$componentsList || !count($componentsList)) {
            return;
        }

        foreach ($componentsList as $components){
            $compId = $components->getComponentId();
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $compId );
            $Warehouse = WarehousePeer::doSelectOne($c);
            //add more requested qty
            $Warehouse->setQtyrequested($Warehouse->getQtyrequested() + $components->getQty1());
            $Warehouse->save();
        }
}

//public function reviseDABOM($newBOM)
//{    
//    if ($newBOM->getReviseId())
//    {
//        $reviseId  = $newBOM->getReviseId();
//        $oldBOM    = BOMPeer::retrieveByPK($reviseId);
//        //Neu bom cu khong ton tai thi return
//        if (!$oldBOM) return;
//        //neu ton tai old bom thi set Status cho oldbom = Revise 
//        //newbom = in progress
//        $oldBOM->setStatus(CommonValues::$gBomStatus['key']['Revised']);
//        $oldBOM->save();
//        //chang status current BOM
//        $newBOM->setStatus(CommonValues::$gBomStatus['key']['In progress']);
//        $newBOM->save();
//        //echo "b1";
//        $c = new Criteria(); $c->add(MRPeer::BOM_ID , $reviseId);
//        $oldMR = MRPeer::doSelectOne($c);
//        $has_oldMR = $oldMR? 1: 0;
//        $oldMRCompGroupId = $has_oldMR ? $oldMR->getComponentgroupId() : null;
//        //Thay doi trang thai cua MR cu
//        if ($has_oldMR)  {
//            $oldMR->setStatus(CommonValues::$gMRStatus['key']['Revised']);
//            $oldMR->save();
//         }
//       //  echo "b2";
//         //Lay ve componentgroupid  cua oldbom va newbom
//        $oldCompGroupId = $oldBOM->getComponentgroupId();
//        $newcompGroupId = $newBOM->getComponentgroupId();
//        if (!$newcompGroupId) return;
//         //Lay ve list components cua BOM moi
//         $c = new Criteria();  
//         $c->add(ComponentsPeer::COMPONENTGROUP_ID , $newcompGroupId);
//         $newcompsList = ComponentsPeer::doSelect($c);
//        //Lay ve list components cua BOM cu
//         $c = new Criteria();  
//         $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldCompGroupId);
//         $oldCompGroupList = ComponentsPeer::doSelect($c);
//           //tao 1 new group component cho MR moi
//         $newMRComponentGroup = new ComponentGroup(); 
//         $newMRComponentGroup->setType(1); 
//         $newMRComponentGroup->save();
//         $newMRComponentGroupId = $newMRComponentGroup->getId();
//         $newMR = new MR();
//         $newMR->setComponentgroupId($newMRComponentGroupId);
//         $newMR->setMrno($oldMR->getMrno());
//         $newMR->setBomId($newBOM->getId());
//         $newMR->setProjectId($newBOM->getProjectId());
//         $newMR->setSaleno( ProjectPeer::retrieveByPK($newMR->getProjectId())->getSaleno());
//         $newMR->setCategory(CommonValues::$gMRCategory['key']['Project']);
//         $newMR->setStatus(CommonValues::$gMRStatus['key']['In progress']);
//         $newMR->setUserId($oldMR->getUserId());
//         $bComplete = true;
//         foreach ($oldCompGroupList as $comps)
//             {
//                if ($comps->getQty4() > 0)
//                       $bComplete = false;
//             }
//          if ($bComplete)
//          {
//          $newMR->setStatus(CommonValues::$gMRStatus['key']['Completed']); 
//          }
//          $newMR->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
//          $newMR->setIsrvresolved(1);             
//          $newMR->setUserId($newBOM->getUserId());
//          $newMR->setReviseId($oldMR->getId());
//          $newMR->save();
//          
//       //   echo "b3";
//        //Duyet qua cac thanh phan cua Bom de kiem tra su thay doi va gan lai cac thanh phan cua MR
//         foreach($newcompsList as $newcomp)
//         {
//              $compId = $newcomp->getComponentId();
//              //Lay ve warehouse de tinh toan tang giam
//              $c = new Criteria();
//              $c->add(WarehousePeer::COMPONENT_ID,$compId);
//              $wareHouse = WarehousePeer::doSelectOne($c);
//              //tuc la component cua oldbom
//              $c = new Criteria();
//              $c->add(ComponentsPeer::COMPONENT_ID,$compId);
//              $c->add(ComponentsPeer::COMPONENTGROUP_ID,$oldCompGroupId);
//              $oldcomp = ComponentsPeer::doSelectOne($c);
//              if ($oldcomp)
//              {
//               $wareHouse->setQtyneeded($wareHouse->getQtyneeded()+($newcomp->getQty1()-$oldcomp->getQty1()));
//             
//              }
//              else
//              {
//                $wareHouse->setQtyneeded($wareHouse->getQtyneeded()+$newcomp->getQty1());
//               
//              }
//              $qtRequestMR = $wareHouse->getQtyneeded()-$wareHouse->getClosing()-$wareHouse->getQtyrequested()-$wareHouse->getQtyordered();
//              if (!$oldcomp)
//              {
//                  $newcompsMR = new Components();
//                  $newcompsMR->setComponentgroupId($newMR->getComponentgroupId());
//                  $newcompsMR->setComponentId($compId);
//                  $newcompsMR->setQty1($qtRequestMR);
//                  $newcompsMR->setQty4($qtRequestMR);
//                  $newcompsMR->setQty2($newcomp->getQty2());
//                  $newcompsMR->setQty3($newcomp->getQty3());
//                  $newcompsMR->save();               
//              }
//              else
//              {
//              // Neu $qtRequestMR < 0 thi van giu lai component cua MR cu
//              //gan no cho MR moi
//              $c = new Criteria();
//              $c->add(ComponentsPeer::COMPONENT_ID,$compId);
//              $c->add(ComponentsPeer::COMPONENTGROUP_ID, $oldMR->getComponentgroupId());
//              $oldcompsMR = ComponentsPeer::doSelectOne($c);
//              $newcompsMR = new Components();
//              $newcompsMR->setComponentgroupId($newMR->getComponentgroupId());
//              $newcompsMR->setComponentId($compId);
//              if ($qtRequestMR <=0)
//              {  
//                  echo "<br>".$qtRequestMR."<br>";
//                  $newcompsMR->setQty1($oldcompsMR->getQty1());
//                  $newcompsMR->setQty4($oldcompsMR->getQty4());
//                  $newcompsMR->setQty2($oldcompsMR->getQty2());
//                  $newcompsMR->setQty3($oldcompsMR->getQty3());                 
//                  $newcompsMR->save();               
//               }
//              else
//              { 
//                  echo "<br>".$qtRequestMR."<br>";
//                  $newcompsMR->setQty1($oldcompsMR->getQty1()+$qtRequestMR);
//                  $newcompsMR->setQty4($oldcompsMR->getQty4()+$qtRequestMR);
//                  $newcompsMR->setQty2($oldcompsMR->getQty2());
//                  $newcompsMR->setQty3($oldcompsMR->getQty3());                 
//                  $newcompsMR->save();
//                  $wareHouse->setQtyrequested($wareHouse->getQtyrequested()+$qtRequestMR); 
//                  
//             }
//           }              
//              $wareHouse->save();
//         }
//         $c = new Criteria();
//         $c->add(POPeer::MRNO,$oldMR->getId());
//         $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Main Component']);
//         $polist = POPeer::doSelect($c);
//         $c = new Criteria();
//         $c->add(MRPeer::MRNO,$oldMR->getMrno());
//         $c->add(MRPeer::APPROVALSTATUS,  CommonValues::$gMRApprovalStatus['key']['Approved']);
//         $c->add(MRPeer::STATUS,  CommonValues::$gMRStatus['key']['In progress']);
//         $c->addOr(MRPeer::STATUS,CommonValues::$gMRStatus['key']['Completed']);
//         $newMR = MRPeer::doSelectOne($c);
//         if (!$newMR) return;
//         echo $newMR->getId()."";
//         foreach ($polist as $po)
//         {          
//            $po->setMrno($newMR->getId());
//            $po->save();
//         }         
//         if ($this->getUser()->hasCredential('APPROVE_MR')){
//                    $approval = new Approval();
//                    $approval->setType( CommonValues::$gApprovalType['key']['MR']);
//                    $approval->setObjectId($newMR->getId());
//                    $approval->setUserId($this->getUser()->getGuardUser()->getId());
//                    $approval->save();
//         }       
//          
//        echo "b4";
//         exit();   
//    }
//}
public function reviseBOM($bom){
    //revise BOM
      if ($bom->getReviseId()){

           $reviseId = $bom->getReviseId();
           $rvBom = BOMPeer::retrieveByPK($reviseId);

           if (!$rvBom) return;

           //change status
           $rvBom->setStatus(CommonValues::$gBomStatus['key']['Revised']);
           $rvBom->save();
           //chang status current BOM
           $bom->setStatus(CommonValues::$gBomStatus['key']['In progress']);
           $bom->save();

           //get MR of revised BOM
           $c = new Criteria(); $c->add(MRPeer::BOM_ID , $reviseId);
           $rvMR = MRPeer::doSelectOne($c);

           $has_rvMR = $rvMR? 1: 0;
           $rvMRCompGroupId = $has_rvMR ? $rvMR->getComponentgroupId() : null;

           //change status
           if ($has_rvMR)  {
               $rvMR->setStatus(CommonValues::$gMRStatus['key']['Revised']);
               $rvMR->save();
           }

           //get componentsbyclient of revised BOM
           $c = new Criteria(); $c->add(ComponentsByClientPeer::BOM_ID , $reviseId);
           $rvCBC = ComponentsByClientPeer::doSelectOne($c);

           $has_rvCBC = $rvCBC ? 1: 0;
           $rvCBCCompGroupId = $has_rvCBC ? $rvCBC->getComponentgroupId() : null;

           //change status
           if ($has_rvCBC) {
               $rvCBC->setStatus(CommonValues::$gCBCStatus['key']['Revised']);
               $rvCBC->save();
           }

           $rvCompGroupId = $rvBom->getComponentgroupId();
           $compGroupId = $bom->getComponentgroupId();

           if (!$compGroupId) return;

           //get comps list of this BOM
           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
           $compsList = ComponentsPeer::doSelect($c);

           //get comps list of revised BOM
           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompGroupId);
           $rvCompsList = ComponentsPeer::doSelect($c);

           //create new component group
           $componentGroup = new ComponentGroup(); $componentGroup->setType(1); $componentGroup->save();
           $MRGroupIdNew = $componentGroup->getId();

           //create new component group
           $componentGroup = new ComponentGroup(); $componentGroup->setType(1); $componentGroup->save();
           $CBCGroupIdNew = $componentGroup->getId();

           //find comps in this BOM with revised
           foreach ($compsList as $comps)  {
               $compId = $comps->getComponentId();

               //get warehouse
               $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
               $warehouse = WarehousePeer::doSelectOne($c);

               //get MR revise comp
               $rvMRComps = null;
               if ($has_rvMR && $rvMRCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvMRCompGroupId);
                   $rvMRComps = ComponentsPeer::doSelectOne($c);
               }

               //get CBC revise comp
               $rvCBCComps = null;
               if ($has_rvCBC && $rvCBCCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCBCCompGroupId);
                   $rvCBCComps = ComponentsPeer::doSelectOne($c);
               }

               //get BOM revise comp
               $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
               $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompGroupId);
               $rvComps = ComponentsPeer::doSelectOne($c);

               //if user add new component then this rvcomp will be null
               if (!$rvComps){
                   $bSupplied = $comps->getQty2()==1? 1: 0;
                   if ($bSupplied){
                       //create CBC comps
                           $compsNew = $comps->copy();
                           $compsNew->setComponentgroupId($CBCGroupIdNew);
                           $compsNew->setQty1($comps->getQty1());
                           $compsNew->setQty2(0);
                           $compsNew->save();
                   }
                   else{
                       //update qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() + $comps->getQty1());

                       $compsNew = $comps->copy();
                       $compsNew->setComponentgroupId($MRGroupIdNew);

                       $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                       if ( $qtytorequest > 0)
                       {
                           $compsNew->setQty1( $qtytorequest);
                           $warehouse->setQtyrequested( $warehouse->getQtyrequested() + $qtytorequest);
                           $compsNew->setQty2(0);
                           $compsNew->save();
                       }
                   }
               }
               //user revise this comp
               else {

                   $bSupplied = $comps->getQty2()==1? 1: 0;
                   $bRvSupplied = $rvComps->getQty2()==1? 1: 0;

                   //but if user change supplied by client
                   if ($bSupplied && !$bRvSupplied){
                       //create CBC comps
                       $compsNew = $comps->copy();
                       $compsNew->setComponentgroupId($CBCGroupIdNew);
                       $compsNew->setQty1($comps->getQty1());
                       $compsNew->setQty2(0);
                       $compsNew->save();


                       //decrease qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() - $rvComps->getQty1()>0? $warehouse->getQtyneeded() - $rvComps->getQty1(): 0);

                       //create MR comps
                       if ($has_rvMR && $rvMRComps){

                           //decrease qty requested
                            $warehouse->setQtyrequested($warehouse->getQtyrequested() - $rvMRComps->getQty1() > 0 ? $warehouse->getQtyrequested() - $rvMRComps->getQty1() : 0);

                            $compsNew = $rvMRComps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->setQty1(0);
                            $compsNew->setQty2(0);
                            $compsNew->save();

                       }

                   }
                   elseif (!$bSupplied && $bRvSupplied){

                       $warehouse->setQtyneeded($warehouse->getQtyneeded() + $comps->getQty1());

                       //closing + in - out
                       $warehouse->setClosing($warehouse->getClosing() + $rvCBCComps->getQty2() - $rvCBCComps->getQty3());
                       $warehouse->setTotalIn($warehouse->getTotalIn() + $rvCBCComps->getQty2());
                       $warehouse->setTotalOut($warehouse->getTotalOut() + $rvCBCComps->getQty3());

                       $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                       if( $qtytorequest > 0 ) {
                            $compsNew = $comps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->setQty1($qtytorequest);
                            $compsNew->setQty4($qtytorequest);
                            $compsNew->save();

                            $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest);
                       }

                   }
                   elseif ($bSupplied && $bRvSupplied){
                       //create CBC comps
                       $compsNew = $rvCBCComps->copy();
                       $compsNew->setComponentgroupId($CBCGroupIdNew);
                       $compsNew->setQty1($comps->getQty1());
                       $compsNew->save();
                   }
                   elseif (!$bSupplied && !$bRvSupplied ){
                       $comps->setQty4($rvComps->getQty4());
                       $comps->save();

                        $extraQty = $comps->getQty1() - $rvComps->getQty1();

                        if ($extraQty == 0) {
                            if ($has_rvMR && $rvMRComps){
                                $compsNew = $rvMRComps->copy();
                                $compsNew->setComponentgroupId($MRGroupIdNew);
                                $compsNew->setQty1($rvMRComps->getQty1());
                                $compsNew->setQty4($rvMRComps->getQty4());
                                $compsNew->save();
                            }
                        }
                        else {

                            //update qty needed in warehouse
                            $qtyneeded = $warehouse->getQtyneeded() + $extraQty;
                            $warehouse->setQtyneeded($qtyneeded > 0 ? $qtyneeded : 0);

                            $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                            $comps->setQty4($comps->getQty4() + $extraQty);                            
                            $comps->save();
                            
                            if ($qtytorequest >= 0 ) {
                                if ($has_rvMR && $rvMRComps) {
                                    $compsNew = $rvMRComps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->setQty1($rvMRComps->getQty1() + $qtytorequest);
                                    $compsNew->setQty4($rvMRComps->getQty4() + $qtytorequest);
                                    $compsNew->save();
                                    $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest);
                                }
                                elseif( $qtytorequest > 0 ) {
                                    $compsNew = $comps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->setQty1($qtytorequest);
                                    $compsNew->setQty4($qtytorequest);
                                    $compsNew->save();

                                    $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest);
                                }

                            }
                            //< 0
                            else {
                                if ($has_rvMR && $rvMRComps) {
                                    $compsNew = $rvMRComps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->setQty1($rvMRComps->getQty1() + $qtytorequest > 0? $rvMRComps->getQty1() + $qtytorequest: 0);
                                    $compsNew->setQty4($rvMRComps->getQty4() + $qtytorequest );
                                    $compsNew->save();

                                    if ($rvMRComps->getQty4() + $qtytorequest >= 0)
                                        $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest > 0? $warehouse->getQtyrequested() + $qtytorequest : 0);
                                    else
                                        $warehouse->setQtyrequested($warehouse->getQtyrequested() - $rvMRComps->getQty4() > 0? $warehouse->getQtyrequested() - $rvMRComps->getQty4() : 0);
                                }
                            }
                        }
                   }

               }
               $warehouse->save();
           }


           //find comps in revised BOM with this BOM
           foreach ($rvCompsList as $rvComps){
               $compId = $rvComps->getComponentId();

               //get warehouse
               $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
               $warehouse = WarehousePeer::doSelectOne($c);

               //get MR revise comp
               $rvMRComps = null;
               if ($has_rvMR && $rvMRCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvMRCompGroupId);
                   $rvMRComps = ComponentsPeer::doSelectOne($c);
               }

               //get CBC revise comp
               $rvCBCComps = null;
               if ($has_rvCBC && $rvCBCCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCBCCompGroupId);
                   $rvCBCComps = ComponentsPeer::doSelectOne($c);
               }

               //get BOM  comps
               $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
               $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
               $comps = ComponentsPeer::doSelectOne($c);

               //if user add new component then this rvcomp will be null
               if (!$comps){
                   $bRvSupplied = $rvComps->getQty2()==1? 1: 0;
                   if ($bRvSupplied){
                       //do nothing
                   }
                   else{
                       //decrease qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() - $rvComps->getQty4()>0? $warehouse->getQtyneeded() - $rvComps->getQty4():0);
                       if ($has_rvMR && $rvMRComps)  {
                            $warehouse->setQtyrequested($warehouse->getQtyrequested() - $rvMRComps->getQty4()>0? $warehouse->getQtyrequested() - $rvMRComps->getQty4(): 0);

                            //create new MR with empty.
                            $compsNew = $rvMRComps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->setQty1(0);
                            $compsNew->setQty4(0);
                            $compsNew->save();
                       }

                   }
               }
               $warehouse->save();
           }

           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRGroupIdNew);
           $compsList = ComponentsPeer::doSelect($c);
           if ($compsList && count($compsList)) {
               $mr = new MR();
               $mr->setComponentgroupId($MRGroupIdNew);
               if ($has_rvMR)
                   $mr->setMrno($rvMR->getMrno());
               else
                    $mr->setMrno(CommonValues::GenerateAutoNumber('MR', null, 'MR'));
               
               if ($has_rvMR) $mr->setReviseId($rvMR->getId());

               $mr->setBomId($bom->getId());
               $mr->setProjectId($bom->getProjectId());
               $mr->setSaleno( ProjectPeer::retrieveByPK($mr->getProjectId())->getSaleno());
               $mr->setCategory(CommonValues::$gMRCategory['key']['Project']);
               $mr->setStatus(CommonValues::$gMRStatus['key']['In progress']);
               
               //check MR complete
               $bComplete = true;
                foreach ($compsList as $comps){
                    if ($comps->getQty4() > 0)
                            $bComplete = false;
                }
                if ($bComplete)
                    $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
                
               $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);

                $approval1 = new Approval();
                $approval1->setType( CommonValues::$gApprovalType['key']['MR']);
                $approval1->setObjectId($mr->getId());
                $approval1->setUserId($this->getUser()->getGuardUser()->getId());
                $approval1->save();

               $c = new Criteria();
               $c->add(POPeer::MRNO, $rvMR->getId());
               $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Main Component']);
               $c->add(POPeer::APPROVALSTATUS, CommonValues::$gMRApprovalStatus['key']['Approved']);
               $po = POPeer::doSelectOne($c);
               if (!$po){
                   $mr->setIsrvresolved(1);
               }
               //set user id for MR
                $mr->setUserId($bom->getUserId());
                $mr->save();

                //if this user have permission with PR_APPROVE_MRMAIN
                //then this MR main was consider approved one times
                if ($this->getUser()->hasCredential('APPROVE_MR')){
                    $approval = new Approval();
                    $approval->setType( CommonValues::$gApprovalType['key']['MR']);
                    $approval->setObjectId($mr->getId());
                    $approval->setUserId($this->getUser()->getGuardUser()->getId());
                    $approval->save();
                }
           }

           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $CBCGroupIdNew);
           $compsList = ComponentsPeer::doSelect($c);
           if ($compsList && count($compsList)) {
                $componentsByClient = new ComponentsByClient();
                $componentsByClient->setComponentgroupId($CBCGroupIdNew);
                $componentsByClient->setBomId($bom->getId());
                $componentsByClient->setProjectId($bom->getProjectId());
                $componentsByClient->setClientId($bom->getClientId());
                $componentsByClient->setStatus(CommonValues::$gCBCStatus['key']['In progress']);

                if ($has_rvCBC) $componentsByClient->setReviseId($rvCBC->getId());

                $componentsByClient->save();
           }
      }
}
public function reviseBOMnew($bom){
    //revise BOM
      if ($bom->getReviseId()){

           $reviseId = $bom->getReviseId();
           $rvBom = BOMPeer::retrieveByPK($reviseId);

           if (!$rvBom) return;

           //change status
           $rvBom->setStatus(CommonValues::$gBomStatus['key']['Revised']);
           $rvBom->save();
           //chang status current BOM
           $bom->setStatus(CommonValues::$gBomStatus['key']['In progress']);
           $bom->save();

           //get MR of revised BOM
           $c = new Criteria(); $c->add(MRPeer::BOM_ID , $reviseId);
           $rvMR = MRPeer::doSelectOne($c);

           $has_rvMR = $rvMR? 1: 0;
           $rvMRCompGroupId = $has_rvMR ? $rvMR->getComponentgroupId() : null;

           //change status
           if ($has_rvMR)  {
               $rvMR->setStatus(CommonValues::$gMRStatus['key']['Revised']);
               $rvMR->save();
           }

           //get componentsbyclient of revised BOM
           $c = new Criteria(); $c->add(ComponentsByClientPeer::BOM_ID , $reviseId);
           $rvCBC = ComponentsByClientPeer::doSelectOne($c);

           $has_rvCBC = $rvCBC ? 1: 0;
           $rvCBCCompGroupId = $has_rvCBC ? $rvCBC->getComponentgroupId() : null;

           //change status
           if ($has_rvCBC) {
               $rvCBC->setStatus(CommonValues::$gCBCStatus['key']['Revised']);
               $rvCBC->save();
           }

           $rvBOMCompGroupId = $rvBom->getComponentgroupId();
           $BOMCompGroupId = $bom->getComponentgroupId();

           if (!$BOMCompGroupId) return;

           //get comps list of this BOM
           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $BOMCompGroupId);
           $BOMCompsList = ComponentsPeer::doSelect($c);

           //get comps list of revised BOM
           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvBOMCompGroupId);
           $rvBOMCompsList = ComponentsPeer::doSelect($c);

           //create new component group
           $componentGroup = new ComponentGroup(); $componentGroup->setType(1); $componentGroup->save();
           $MRGroupIdNew = $componentGroup->getId();

           //create new component group
           $componentGroup = new ComponentGroup(); $componentGroup->setType(1); $componentGroup->save();
           $CBCGroupIdNew = $componentGroup->getId();

           //find comps in this BOM with revised
           foreach ($BOMCompsList as $BOMComps)  
           {
               $compId = $BOMComps->getComponentId();

               //get warehouse
               $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
               $warehouse = WarehousePeer::doSelectOne($c);

               //get MR revise comp
               $rvMRComps = null;
               if ($has_rvMR && $rvMRCompGroupId) 
               {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvMRCompGroupId);
                   $rvMRComps = ComponentsPeer::doSelectOne($c);
               }

               //get CBC revise comp
               $rvCBCComps = null;
               if ($has_rvCBC && $rvCBCCompGroupId) 
               {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCBCCompGroupId);
                   $rvCBCComps = ComponentsPeer::doSelectOne($c);
               }

               //get BOM revise comp
               $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
               $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvBOMCompGroupId);
               $rvBOMComps = ComponentsPeer::doSelectOne($c);

               //if user add new component then this rvcomp will be null
               if (!$rvBOMComps)
               {
                   $bSupplied = $BOMComps->getQty2()==1? 1: 0;
                   if ($bSupplied)
                   {
                       //create CBC comps
                           $compsNew = $BOMComps->copy();
                           $compsNew->setComponentgroupId($CBCGroupIdNew);
                           $compsNew->setQty1($BOMComps->getQty1());
                           //reset lai gia tri nay tu BOM comps
                           $compsNew->setQty2(0);
                           $compsNew->save();
                   }
                   else
                   {
                       //update qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() + $BOMComps->getQty1());

                       $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                       if ( $qtytorequest > 0)
                       {
                           $warehouse->setQtyrequested( $warehouse->getQtyrequested() + $qtytorequest);
                           
                           $compsNew = $BOMComps->copy();
                           $compsNew->setComponentgroupId($MRGroupIdNew);
                           $compsNew->setQty1( $qtytorequest);
                           $compsNew->setQty4( $qtytorequest);                           
                           $compsNew->setQty2(0);
                           $compsNew->save();
                       }
                   }
               }
               //user revise this comp
               else 
               {

                   $bSupplied = $BOMComps->getQty2()==1? 1: 0;
                   $bRvSupplied = $rvBOMComps->getQty2()==1? 1: 0;

                   //but if user change supplied by client
                   if ($bSupplied && !$bRvSupplied){
                       //create CBC comps
                       $compsNew = $BOMComps->copy();
                       $compsNew->setComponentgroupId($CBCGroupIdNew);
                       $compsNew->setQty1($BOMComps->getQty1());
                       $compsNew->setQty2(0);
                       $compsNew->save();

                       //decrease qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() - $rvBOMComps->getQty1()>0? $warehouse->getQtyneeded() - $rvBOMComps->getQty1(): 0);

                       //create MR comps
                       if ($has_rvMR && $rvMRComps)
                       {

                            $compsNew = $rvMRComps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->save();
                       }
                   }
                   elseif (!$bSupplied && $bRvSupplied)
                   {

                       $warehouse->setQtyneeded($warehouse->getQtyneeded() + $BOMComps->getQty1());

                       $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                       if( $qtytorequest > 0 ) 
                       {
                           $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest);
                           
                            $compsNew = $BOMComps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->setQty1($qtytorequest);
                            $compsNew->setQty4($qtytorequest);
                            $compsNew->save();                            
                       }

                   }
                   elseif ($bSupplied && $bRvSupplied)
                   {
                       //create CBC comps
                       $compsNew = $rvCBCComps->copy();
                       $compsNew->setComponentgroupId($CBCGroupIdNew);
                       $compsNew->setQty1($BOMComps->getQty1());
                       $compsNew->save();
                   }
                   elseif (!$bSupplied && !$bRvSupplied )
                   {
                       //set qty outstanding cho BOM moi
                       $BOMComps->setQty4($rvBOMComps->getQty4());
                       $BOMComps->save();

                        $extraQty = $BOMComps->getQty1() - $rvBOMComps->getQty1();

                        if ($extraQty == 0) 
                        {
                            if ($has_rvMR && $rvMRComps)
                            {
                                $compsNew = $rvMRComps->copy();
                                $compsNew->setComponentgroupId($MRGroupIdNew);
                                $compsNew->save();
                            }
                        }
                        else {

                            //update qty needed in warehouse
                            $warehouse->setQtyneeded($warehouse->getQtyneeded() + $extraQty > 0 ? $warehouse->getQtyneeded() + $extraQty : 0);

                            $qtytorequest = $warehouse->getQtyneeded() - $warehouse->getClosing() - $warehouse->getQtyrequested() - $warehouse->getQtyordered();

                            $BOMComps->setQty4($rvBOMComps->getQty4() + $extraQty);                            
                            $BOMComps->save();
                            
                            if ($qtytorequest > 0 ) 
                            {
                                if ($has_rvMR && $rvMRComps) 
                                {
                                    $compsNew = $rvMRComps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->setQty1($rvMRComps->getQty1() + $qtytorequest);
                                    $compsNew->setQty4($rvMRComps->getQty4() + $qtytorequest);
                                    $compsNew->save();                                    
                                }
                                else
                                {
                                    $compsNew = $BOMComps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->setQty1($qtytorequest);
                                    $compsNew->setQty2(0);
                                    $compsNew->setQty3(0);
                                    $compsNew->setQty4($qtytorequest);
                                    $compsNew->save();
                                }
                                
                                $warehouse->setQtyrequested($warehouse->getQtyrequested() + $qtytorequest);
                            }
                            //<= 0 thi giu lai
                            else 
                            {
                                if ($has_rvMR && $rvMRComps) 
                                {
                                    $compsNew = $rvMRComps->copy();
                                    $compsNew->setComponentgroupId($MRGroupIdNew);
                                    $compsNew->save();
                                }
                            }
                        }
                   }

               }
               $warehouse->save();
           }


           //find comps in revised BOM with this BOM
           foreach ($rvBOMCompsList as $rvBOMComps){
               $compId = $rvBOMComps->getComponentId();

               //get warehouse
               $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
               $warehouse = WarehousePeer::doSelectOne($c);

               //get MR revise comp
               $rvMRComps = null;
               if ($has_rvMR && $rvMRCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvMRCompGroupId);
                   $rvMRComps = ComponentsPeer::doSelectOne($c);
               }

               //get CBC revise comp
               $rvCBCComps = null;
               if ($has_rvCBC && $rvCBCCompGroupId) {
                   $c = new Criteria();
                   $c->add(ComponentsPeer::COMPONENT_ID , $compId);
                   $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCBCCompGroupId);
                   $rvCBCComps = ComponentsPeer::doSelectOne($c);
               }

               //get BOM  comps
               $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
               $c->add(ComponentsPeer::COMPONENTGROUP_ID , $BOMCompGroupId);
               $BOMComps = ComponentsPeer::doSelectOne($c);

               //if user add new component then this rvcomp will be null
               if (!$BOMComps)
               {
                   $bRvSupplied = $rvBOMComps->getQty2()==1? 1: 0;
                   if ($bRvSupplied)
                   {
                       //do nothing
                   }
                   else
                   {
                       //decrease qty needed
                       $warehouse->setQtyneeded($warehouse->getQtyneeded() - $rvBOMComps->getQty1() > 0 ? $warehouse->getQtyneeded() - $rvBOMComps->getQty1() : 0);
                       if ($has_rvMR && $rvMRComps)  
                       {
                            //create new MR with empty.
                            $compsNew = $rvMRComps->copy();
                            $compsNew->setComponentgroupId($MRGroupIdNew);
                            $compsNew->save();
                       }
                   }
               }
               $warehouse->save();
           }

           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $MRGroupIdNew);
           $MRCompsList = ComponentsPeer::doSelect($c);
           if ($MRCompsList && count($MRCompsList)) 
           {
               $mr = new MR();
               $mr->setComponentgroupId($MRGroupIdNew);
               if ($has_rvMR)
                   $mr->setMrno($rvMR->getMrno());
               else
                    $mr->setMrno(CommonValues::GenerateAutoNumber('MR', null, 'MR'));
               
               if ($has_rvMR) $mr->setReviseId($rvMR->getId());

               $mr->setBomId($bom->getId());
               $mr->setProjectId($bom->getProjectId());
               $mr->setSaleno( ProjectPeer::retrieveByPK($mr->getProjectId())->getSaleno());
               $mr->setCategory(CommonValues::$gMRCategory['key']['Project']);
               $mr->setStatus(CommonValues::$gMRStatus['key']['In progress']);
               
               //check MR complete
               $bComplete = true;
                foreach ($MRCompsList as $MRComps)
                {
                    if ($MRComps->getQty4() > 0)
                        $bComplete = false;
                }
                if ($bComplete)
                    $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
                
               $mr->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
               
                $approval = new Approval();
                $approval->setType( CommonValues::$gApprovalType['key']['MR']);
                $approval->setObjectId($mr->getId());
                $approval->setUserId($this->getUser()->getGuardUser()->getId());
                $approval->save();
                
                //set da resolved
               $mr->setIsrvresolved(1);
               
               //set user id for MR
                $mr->setUserId($bom->getUserId());
                $mr->save();       
               
               //link tat ca po tu mr cu sang mr moi
               if ($has_rvMR && $rvMR)
               {
                   $c = new Criteria();
                   $c->add(POPeer::MRNO, $rvMR->getId());
                   $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Main Component']);
                   $ListPO = POPeer::doSelect($c);
                   foreach ($ListPO as $PO)
                   {                   
                       $PO->setMrno($mr->getId());
                       $PO->save();
                   }               
               }
           }

           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $CBCGroupIdNew);
           $CBCCompsList = ComponentsPeer::doSelect($c);
           if ($CBCCompsList && count($CBCCompsList)) {
                $componentsByClient = new ComponentsByClient();
                $componentsByClient->setComponentgroupId($CBCGroupIdNew);
                $componentsByClient->setBomId($bom->getId());
                $componentsByClient->setProjectId($bom->getProjectId());
                $componentsByClient->setClientId($bom->getClientId());
                $componentsByClient->setStatus(CommonValues::$gCBCStatus['key']['In progress']);

                if ($has_rvCBC) $componentsByClient->setReviseId($rvCBC->getId());

                $componentsByClient->save();
           }
      }
}  
 
public function reviseDAMR($newMR,$module)
{
     $statuspo = false;
      if ($newMR->getReviseId()){

           $reviseId = $newMR->getReviseId();
           if ($module=='MRSUB')
                $oldMR = MR2Peer::retrieveByPK($reviseId);
           else $oldMR = MR3Peer::retrieveByPK($reviseId);

           if (!$oldMR){
               echo "ERROR: Khong co revise MR";
               exit();
           }
           $oldMR->setStatus(CommonValues::$gBomStatus['key']['Revised']);
           $oldMR->save();
           //chang status current MR
           //Luu MR MOI           
           $newMR->setStatus(CommonValues::$gBomStatus['key']['In progress']);
           $newMR->setIsrvresolved(0);
           /*
           $c = new Criteria();
           $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldCompGroupId);
           $compsoldList = ComponentsPeer::doSelect($c);
           $bComplete = true;
            foreach ($compsoldList as $comps){
            if ($comps->getQty4() > 0)
                $bComplete = false;
            }
            if ($bComplete)
            {
                $mrnew->setStatus(CommonValues::$gMRStatus['key']['Completed']);
                $mr->save();
            }
            * 
            */
           $newMR->save();
           $oldcompGroupId = $oldMR->getComponentgroupId();
           $newcompGroupId = $newMR->getComponentgroupId();
           if (!$newcompGroupId){
               echo "ERROR: Khong co component group id";
               exit();
           }
          //Lay ve list component cua MR moi
           $c = new Criteria();   
           $c->add(ComponentsPeer::COMPONENTGROUP_ID , $newcompGroupId);
           $newcompsList = ComponentsPeer::doSelect($c);
           //get comps list of revised BOM
           $c = new Criteria(); 
           $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldcompGroupId);
           $oldCompsList = ComponentsPeer::doSelect($c);
           //Lay ve component cu MR cu
          // echo "b1";
             foreach ($newcompsList as $comps)  {
                 //lay ve id cua 1 component trong MR moi
               $compId = $comps->getComponentId();
               //lay ve warehouse de cap nhat lai so luong revise //
               $c = new Criteria();    
               $c->add(WarehousePeer::COMPONENT_ID , $compId);
               $wareHouse = WarehousePeer::doSelectOne($c);
               
               //Lay 1 component cua revise MR de so sanh revise tang hay giam
               $c = new Criteria();   
               $c->add(ComponentsPeer::COMPONENT_ID , $compId);
               $c->add(ComponentsPeer::COMPONENTGROUP_ID , $oldcompGroupId);
               $oldComps = ComponentsPeer::doSelectOne($c);

               //if user add new component then this rvcomp will be null
               if (!$oldComps){
                   $wareHouse->setQtyrequested($wareHouse->getQtyrequested() + $comps->getQty1());
                   $wareHouse->setQtyneeded($wareHouse->getQtyneeded() + $comps->getQty1());
                   $comps->setQty4($comps->getQty1());                   
                   $comps->save();
               }
               //Khi user revise component nay thi kiem tra
               else
               {
                   //set lai qty outstanding
                   $comps->setQty4($oldComps->getQty4());
                   //---$comps->save();
                   $delta = $comps->getQty1() - $oldComps->getQty1();
                   if ($delta == 0 ){                       
                       continue;
                   }
                 
                   //Khi revise ma tang thi luu vao khong can quan tam
                   if ($delta > 0){
                       //cap nhat lai so luong revise tang
                       $wareHouse->setQtyrequested($wareHouse->getQtyrequested() + $delta);                       
                       $comps->setQty4($comps->getQty4() + $delta);
                       $comps->save();
                        $statuspo = true;
                   } 
                   //khi revise giam
                   //giam suong dem muc bang tong cac component cua PO ma dang o trang thai la Partial va Full receiv
                   else{
                        $c = new Criteria();
                        $c->add(POPeer::APPROVALSTATUS,  CommonValues::$gMRApprovalStatus['key']['Approved']);
                        $c->add(POPeer::RECEIVEDSTATUS,  CommonValues::$gPOReceivedStatus['key']['Partially Received']);
                        $c->addOr(POPeer::RECEIVEDSTATUS,  CommonValues::$gPOReceivedStatus['key']['Fully Received']);
                        if ($module=="MRSUB")
                        {
                           $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Sub Component']);
                           $c->add(POPeer::MRNO,$oldMR->getId());
                           
                        }
                        else
                        {
                           $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Raw Material']);
                           $c->add(POPeer::MRNO,$oldMR->getId());  
                        }
                        $polistcheck = POPeer::doSelect($c);
                        //tinh tong po de kiem tra so luong can giam cho conponent cua mr moi
                        $sumpotocheck = 0;
                        foreach ($polistcheck as $po)
                        {
                            $c = new Criteria();
                            $c->add(ComponentsPeer::COMPONENT_ID,$compId);
                            $c->add(ComponentsPeer::COMPONENTGROUP_ID,$po->getComponentgroupId());
                            $compspo = ComponentsPeer::doSelectOne($c);
                            $sumpotocheck += $compspo->getQty1();
                        }
                        // Neu ma so luong giam nho hon tong so luong cua 1 component thi cho $delta =0
                        //so luong thay doi dung bang so luong da order
                        if ($comps->getQty1() <$sumpotocheck)
                        {
                            $comps->setQty1($sumpotocheck) ;
                            $delta   = $comps->getQty1()- $oldComps->getQty1();                            
                        }
                        //cap nhat lai so luong revise giam
                       $wareHouse->setQtyrequested($wareHouse->getQtyrequested() + $delta);                       
                       $comps->setQty4($comps->getQty4() + $delta);
                       $comps->save();
                   }
                   echo $delta."<br>";
                   // $wareHouse->setQtyneeded($wareHouse->getQtyneeded() + $delta); 
                
               }
               $wareHouse->save();
           }
         $c = new Criteria();
         $c->add(POPeer::MRNO,$oldMR->getId());
         if ($module == 'MRSUB')
         $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Sub Component']);
         else
         $c->add(POPeer::COMPCATEGORY,  CommonValues::$gCompCategory['key']['Raw Material']);    
         $polist = POPeer::doSelect($c);
         foreach ($polist as $po)
         {
            if ($po->getReceivedstatus() == CommonValues::$gPOReceivedStatus['key']['Fully Received'] &&  $statuspo)
            {
                $po->getReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Partially Received']);
            }
            $po->setMrno($mrnew->getMrno());
            $po->save();
         }   
         // echo "b4";
        //  exit();
           //Ket thuc lap cac component
   
      }
      ///Ket thuc
    
}


public function reviseMR($mr, $module)
{
    //revise BOM
    if ($mr->getReviseId())
    {

        $reviseId = $mr->getReviseId();
        if ($module=='MRSUB')
           $rvMR = MR2Peer::retrieveByPK($reviseId);
        else 
           $rvMR = MR3Peer::retrieveByPK($reviseId);

        if (!$rvMR)
        {
           echo "ERROR: Khong co revise MR";
           exit();
        }

        //change status
        $rvMR->setStatus(CommonValues::$gBomStatus['key']['Revised']);
        $rvMR->save();
        //chang status current MR
        $mr->setStatus(CommonValues::$gBomStatus['key']['In progress']);
        $mr->setIsrvresolved(0);
        $mr->save();

        $rvCompGroupId = $rvMR->getComponentgroupId();
        $compGroupId = $mr->getComponentgroupId();

        if (!$compGroupId)
        {
           echo "ERROR: Khong co component group id";
           exit();
        }

        //get comps list of this BOM
        $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
        $compsList = ComponentsPeer::doSelect($c);

        //get comps list of revised BOM
        $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompGroupId);
        $rvCompsList = ComponentsPeer::doSelect($c);


        //find comps in this BOM with revised
        foreach ($compsList as $comps)  {
            $compId = $comps->getComponentId();

            //get warehouse
            $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
            $warehouse = WarehousePeer::doSelectOne($c);

            //get MR revise comp
            $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
            $c->add(ComponentsPeer::COMPONENTGROUP_ID , $rvCompGroupId);
            $rvComps = ComponentsPeer::doSelectOne($c);

            //if user add new component then this rvcomp will be null
            if (!$rvComps){
               $warehouse->setQtyrequested($warehouse->getQtyrequested() + $comps->getQty1());               
               $comps->setQty4($comps->getQty1());                   
               $comps->save();
            }
            //user revise this comp
            else
            {
               $delta = $comps->getQty1() - $rvComps->getQty1();
               
               if ($delta == 0 )
               {
                   //set lai qty outstanding
                   $comps->setQty4($rvComps->getQty4());
                   $comps->save();
               }
               
               if ($rvComps->getQty4() + $delta < 0)
               {
                   $comps->setQty4($rvComps->getQty4() + $delta);
                   $comps->save();
               }
               else
               {
                   
               }
                       
               if ($delta > 0)
               {
                   $warehouse->setQtyrequested($warehouse->getQtyrequested() + $delta);                       
                   $comps->setQty4($comps->getQty4() + $delta);
                   $comps->save();
               } 
               else
               {
                   if ($comps->getQty4() + $delta >= 0){
                       $warehouse->setQtyrequested($warehouse->getQtyrequested() + $delta > 0?
                               $warehouse->getQtyrequested() + $delta : 0);
                   }else{
                       $warehouse->setQtyrequested($warehouse->getQtyrequested() - $comps->getQty4() > 0?
                               $warehouse->getQtyrequested() - $comps->getQty4(): 0);
                   }

                   $comps->setQty4($rvComps->getQty4() + $delta);
                   $comps->save();
               }

            }
            $warehouse->save();
        }


        //find comps in revised MR with this MR
        foreach ($rvCompsList as $rvComps){
           $compId = $rvComps->getComponentId();

           //get warehouse
           $c = new Criteria();    $c->add(WarehousePeer::COMPONENT_ID , $compId);
           $warehouse = WarehousePeer::doSelectOne($c);

           //get MR  comps
           $c = new Criteria();    $c->add(ComponentsPeer::COMPONENT_ID , $compId);
           $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
           $comps = ComponentsPeer::doSelectOne($c);

           //if user add new component then this rvcomp will be null
           if (!$comps){
               $delta = - $rvComps->getQty1();
               $warehouse->setQtyneeded($warehouse->getQtyneeded() + $delta);

               if ($rvComps->getQty4() + $delta >= 0){
                   $warehouse->setQtyrequested($warehouse->getQtyrequested() + $delta > 0?
                           $warehouse->getQtyrequested() + $delta : 0);
               }else{
                   $warehouse->setQtyrequested($warehouse->getQtyrequested() - $rvComps->getQty4() > 0?
                           $warehouse->getQtyrequested() - $rvComps->getQty4(): 0);
               }
           }
           $warehouse->save();
        }
        //resolved when there is no PO
        $c = new Criteria();
        $c->add(POPeer::MRNO, $rvMR->getId());

        if ($module=='MRSUB')
            $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Sub Component']);
        else
            $c->add(POPeer::COMPCATEGORY, CommonValues::$gCompCategory['key']['Raw Material']);

        $c->add(POPeer::APPROVALSTATUS, CommonValues::$gMRApprovalStatus['key']['Approved']);
        $po = POPeer::doSelectOne($c);
        if (!$po){
           $mr->setIsrvresolved(1);
           $mr->save();
        }

        //check MR completed
        $c = new Criteria();    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
        $compsList = ComponentsPeer::doSelect($c);
        $bComplete = true;
        foreach ($compsList as $comps){
        if ($comps->getQty4() > 0)
            $bComplete = false;
        }
        if ($bComplete)
        {
            $mr->setStatus(CommonValues::$gMRStatus['key']['Completed']);
            $mr->save();
        }
    }      
}

public function approveBOM($bom){

     //get component group list to get list components
        $componentGroupId = $bom->getComponentgroupId();
        if (!$componentGroupId) {
            return;
        }

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
        $componentsList = ComponentsPeer::doSelect($c);
        if (!count($componentsList)){
            return;
        }

        //check create MR, components by client if any
        $createMR = false;
        $createComponentsByClient = false;
        foreach ($componentsList as $components) {
                //condition for create new MR
                $componentId = $components->getComponentId();
                $c1 = new Criteria();
                $c1->add(WarehousePeer::COMPONENT_ID , $componentId);
                $Warehouse = WarehousePeer::doSelectOne($c1);

                if (!$Warehouse)  return;
                
                //condition for create components by client object
                if (1 == $components->getQty2())
                   $createComponentsByClient = true;
                else
                {
                    //add more qty need
                    $Warehouse->setQtyneeded($Warehouse->getQtyneeded() + $components->getQty1());
                    $Warehouse->save();
                    
                    //condition for create MR
                    if ($Warehouse->getQtyneeded() - $Warehouse->getClosing() - $Warehouse->getQtyordered() - $Warehouse->getQtyrequested() > 0 )
                        $createMR= true;
                }
        }

        //create components by client
        if ($createComponentsByClient){
           $componentsByClient = new ComponentsByClient();
           $componentsByClient->setBomId($bom->getId());
           $componentsByClient->setProjectId($bom->getProjectId());
           $componentsByClient->setClientId($bom->getClientId());
           //create ComponentGroup
            $componentGroupx = new  ComponentGroup();
            $componentGroupx->setType(1);
            $componentGroupx->save();
            $CBCCompGroupId = $componentGroupx->getId();
            $componentsByClient->setComponentgroupId($CBCCompGroupId);
            $componentsByClient->setStatus(CommonValues::$gCBCStatus['key']['In progress']);
            $componentsByClient->save();

           foreach ($componentsList as $components) {
                    if (1 == $components->getQty2()){
                       $componentsNew = new Components();
                       $componentsNew->setComponentId($components->getComponentId());
                       $componentsNew->setComponentgroupId($CBCCompGroupId);
                       $componentsNew->setQty1($components->getQty1());
                       $componentsNew->save();
                    }
           }
        }

        //create MR
        if ($createMR){

           //Create new MR
           $MR = new MR();
           $default = CommonValues::GenerateAutoNumber('MR', null, 'MR');

            //set properties for new MR
            $MR->setMrno($default);
            $MR->setBomId($bom->getId());
            $MR->setProjectId($bom->getProjectId());

            //set saleno
            $project = ProjectPeer::retrieveByPK($bom->getProjectId());
            $MR->setSaleno($project->getSaleno());

            $MR->setCategory(CommonValues::$gMRCategory['key']['Project']);
            $MR->setStatus(CommonValues::$gMRStatus['key']['In progress']);
            $MR->setApprovalstatus(CommonValues::$gMRApprovalStatus['key']['Approved']);
            
            $MR->setPublishtime(time());

            $approval = new Approval();
            $approval->setType( CommonValues::$gApprovalType['key']['MR']);
            $approval->setObjectId($MR->getId());
            $approval->setUserId($this->getUser()->getGuardUser()->getId());
            $approval->save();

            //create ComponentGroup
            $componentGroup = new  ComponentGroup();
            $componentGroup->setType(2);            
            $componentGroup->save();
            
            $MRCompGroupId = $componentGroup->getId();

            //set component group id for MR
            $MR->setComponentgroupId($MRCompGroupId);

            //set user id for MR main
            $MR->setUserId($bom->getUserId());
            
            $MR->save();            

            //create component list for MR
            foreach ($componentsList as $components) {
            //condition for create new MR
                $componentId = $components->getComponentId();
                $c1 = new Criteria();
                $c1->add(WarehousePeer::COMPONENT_ID , $componentId);
                $Warehouse = WarehousePeer::doSelectOne($c1);
                
                $qtyToRequest = $Warehouse->getQtyneeded() - $Warehouse->getClosing() - $Warehouse->getQtyordered() - $Warehouse->getQtyrequested();

                if (1 != $components->getQty2()  &&  $qtyToRequest > 0 ){

                    //create new components
                    $componentsNew = new Components();
                    $componentsNew->setComponentId($componentId);
                    $componentsNew->setComponentgroupId($MRCompGroupId);
                    $componentsNew->setQty1($qtyToRequest);
                    $componentsNew->setQty4($qtyToRequest);
                    $componentsNew->setDate($components->getDate());
                    
                    $componentsNew->save();
                    
                    //add more qty requested
                    $Warehouse->setQtyrequested($Warehouse->getQtyrequested() + $qtyToRequest);
                }
                $Warehouse->save();
            }

        }
}

}
